import React, { useCallback, useState, useEffect } from 'react';
import { useTemplate } from '@/contexts/template';
import type { CheckItemTemplate, CheckItemType, AssessmentType } from '@/types/template';
import { FileUp, Download, X } from 'lucide-react';
import * as XLSX from 'xlsx-js-style';
import { read, utils } from 'xlsx-js-style';
import Papa from 'papaparse';
import type { TemplateTable } from '@/types/template';

export function FileUploadStep({ onNext }: { onNext: () => void }) {
  const { 
    state: { currentTemplate },
    setCurrentTemplate
  } = useTemplate();
  
  const [isDragging, setIsDragging] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [templateName, setTemplateName] = useState(currentTemplate?.name || '新模板');
  const [templateDescription, setTemplateDescription] = useState(currentTemplate?.description || '');
  const [assessmentType, setAssessmentType] = useState<AssessmentType>(currentTemplate?.assessment_type || '101');

  // Update local state when currentTemplate changes
  useEffect(() => {
    if (currentTemplate) {
      setTemplateName(currentTemplate.name);
      setTemplateDescription(currentTemplate.description);
      setAssessmentType(currentTemplate.assessment_type);
    }
  }, [currentTemplate]);

  const handleDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      setSelectedFile(e.dataTransfer.files[0]);
    }
  }, []);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setSelectedFile(e.target.files[0]);
    }
  };

  const handleRemoveFile = () => {
    setSelectedFile(null);
  };

  const parseFile = async (file: File): Promise<CheckItemTemplate[]> => {
    const fileExtension = file.name.split('.').pop()?.toLowerCase();
    
    if (fileExtension === 'xlsx' || fileExtension === 'xls') {
      return parseExcelFile(file);
    } else if (fileExtension === 'csv') {
      return parseCsvFile(file);
    } else {
      throw new Error('不支持的文件格式，请上传 .xlsx, .xls 或 .csv 文件');
    }
  };

  const parseExcelFile = async (file: File): Promise<CheckItemTemplate[]> => {
    const data = await file.arrayBuffer();
    const workbook = read(data);
    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = utils.sheet_to_json<any>(firstSheet, { header: 1 });
    
    return processFileData(jsonData);
  };

  const parseCsvFile = (file: File): Promise<CheckItemTemplate[]> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      
      reader.onload = (event) => {
        try {
          if (!event.target?.result) {
            throw new Error('无法读取文件内容');
          }
          
          const text = event.target.result as string;
          
          const parseResult = Papa.parse<string[]>(text, {
            skipEmptyLines: true,
          });
          
          try {
            const items = processFileData(parseResult.data);
            resolve(items);
          } catch (error) {
            reject(error);
          }
        } catch (error) {
          reject(error);
        }
      };
      
      reader.onerror = () => {
        reject(new Error('读取文件时出错'));
      };
      
      reader.readAsText(file, 'UTF-8');
    });
  };

  const isValidCheckItemType = (type: string): boolean => {
    return ['风险项', '保障项'].includes(type);
  };

  const processFileData = (data: string[][]): CheckItemTemplate[] => {
    if (data.length < 2) {
      throw new Error('文件内容不能为空');
    }

    // 只有评估类型为105（数据安全评估）时才需要成熟度等级
    const showMaturityLevel = assessmentType === '105';

    // 验证表头
    const headers = data[0].map((h: string) => h?.trim().toLowerCase());
    const baseRequiredHeaders = ['标题', '描述', '指引', '类型'];
    const requiredHeaders = showMaturityLevel 
      ? [...baseRequiredHeaders, '成熟度等级']
      : baseRequiredHeaders;
    const missingHeaders = requiredHeaders.filter(h => !headers.includes(h.toLowerCase()));
    
    if (missingHeaders.length > 0) {
      throw new Error(`缺少必要的列: ${missingHeaders.join(', ')}`);
    }

    // 处理数据行
    return data.slice(1).map((row, index) => {
      // 确保行数据有足够的列
      const rowData = Array.isArray(row) ? row : [];
      
      const dataType = String(rowData[headers.indexOf('类型')] || '风险项').trim();
      
      if (!isValidCheckItemType(dataType)) {
        throw new Error(`第 ${index + 2} 行: 无效的类型 "${dataType}"，请使用 "风险项" 或 "保障项"`);
      }

      // 构建基础项
      const baseItem = {
        id: `item-${Date.now()}-${index}`,
        title: String(rowData[headers.indexOf('标题')] || '').trim(),
        description: String(rowData[headers.indexOf('描述')] || '').trim(),
        guide: String(rowData[headers.indexOf('指引')] || '').trim(),
        compliance_type: dataType === '风险项' ? 'risk' : 'guarantee' as CheckItemType,
      };

      // 只有评估类型为105时才解析并添加成熟度等级
      if (showMaturityLevel) {
        const maturityLevelStr = String(rowData[headers.indexOf('成熟度等级')] || '1').trim();
        const maturityLevel = parseInt(maturityLevelStr) || 1;
        
        if (maturityLevel < 1 || maturityLevel > 5) {
          throw new Error(`第 ${index + 2} 行: 成熟度等级必须在 1-5 之间，当前值为 "${maturityLevelStr}"`);
        }
        
        return {
          ...baseItem,
          maturity_level: maturityLevel,
        };
      }
      
      return baseItem;
    }).filter(item => item.title); // 过滤掉空标题的行
  };

  const handleUpload = async () => {
    if (!selectedFile) return;
    
    setIsLoading(true);
    
    try {
      const items = await parseFile(selectedFile);
      
      if (items.length === 0) {
        throw new Error('文件中没有有效的检查项');
      }
      
      const currentTemplate : TemplateTable = {
        id: `table-${Date.now()}`,
        name: templateName,
        description: templateDescription,
        assessment_type: assessmentType,
        items: items
      }

      setCurrentTemplate(currentTemplate);
      onNext();
    } catch (error) {
      console.error('Error processing file:', error);
      alert(error instanceof Error ? error.message : '处理文件时发生错误');
    } finally {
      setIsLoading(false);
    }
  };

  const downloadTemplate = () => {
    // 只有评估类型为105（数据安全评估）时才包含成熟度等级列
    const showMaturityLevel = assessmentType === '105';
    
    // 创建示例数据
    const templateData = showMaturityLevel
      ? [
          ['标题', '描述', '指引', '类型', '成熟度等级'],
          ['密码策略检查', '检查密码复杂度要求是否满足', '1. 检查密码最小长度\n2. 检查密码复杂度要求\n3. 检查密码历史记录', '保障项', '1'],
          ['访问控制检查', '检查用户权限分配是否正确', '1. 检查管理员权限分配\n2. 检查普通用户权限\n3. 检查访客权限', '保障项', '2'],
          ['日志审计检查', '检查系统日志是否完整', '1. 检查日志存储周期\n2. 检查日志完整性\n3. 检查日志访问控制', '保障项', '3']
        ]
      : [
          ['标题', '描述', '指引', '类型'],
          ['密码策略检查', '检查密码复杂度要求是否满足', '1. 检查密码最小长度\n2. 检查密码复杂度要求\n3. 检查密码历史记录', '风险项'],
          ['访问控制检查', '检查用户权限分配是否正确', '1. 检查管理员权限分配\n2. 检查普通用户权限\n3. 检查访客权限', '保障项'],
          ['日志审计检查', '检查系统日志是否完整', '1. 检查日志存储周期\n2. 检查日志完整性\n3. 检查日志访问控制', '风险项']
        ];

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(templateData);
    
    // 设置列宽
    ws['!cols'] = showMaturityLevel
      ? [
          { wch: 30 }, // 标题
          { wch: 50 }, // 描述
          { wch: 60 }, // 指引
          { wch: 15 }, // 类型
          { wch: 15 }  // 成熟度等级
        ]
      : [
          { wch: 30 }, // 标题
          { wch: 50 }, // 描述
          { wch: 60 }, // 指引
          { wch: 15 }  // 类型
        ];
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '检查项模板');
    
    // 生成Excel文件并下载
    XLSX.writeFile(wb, '检查项模板.xlsx');
  };

  return (
    <div className="space-y-6">
      <div className="space-y-2">
        <h3 className="text-lg font-medium">上传检查项模板文件</h3>
        <p className="text-sm text-slate-500">
          支持 Excel (.xlsx, .xls) 或 CSV 格式文件
        </p>
      </div>

      <div className="space-y-4">
        <div className="space-y-2">
          <label className="block text-sm font-medium text-slate-700">
            模板名称 <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            value={templateName}
            onChange={(e) => setTemplateName(e.target.value)}
            className="block w-full rounded-md border border-slate-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2"
            placeholder="输入模板名称"
            required
          />
        </div>

        <div className="space-y-2">
          <label className="block text-sm font-medium text-slate-700">
            模板描述
          </label>
          <textarea
            value={templateDescription}
            onChange={(e) => setTemplateDescription(e.target.value)}
            className="block w-full rounded-md border border-slate-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2"
            placeholder="输入模板描述"
            rows={3}
          />
        </div>

        <div className="space-y-2">
          <label className="block text-sm font-medium text-slate-700">
            评估类型 <span className="text-red-500">*</span>
          </label>
          <select
            value={assessmentType}
            onChange={(e) => setAssessmentType(e.target.value as AssessmentType)}
            className="block w-full rounded-md border border-slate-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2 bg-white"
          >
            <option value="101">互联网新技术新业务安全评估 (101)</option>
            <option value="102">新业务涉诈风险安全评估 (102)</option>
            <option value="103">智慧中台评估 (103)</option>
            <option value="104">5G应用安全评估 (104)</option>
            <option value="105">数据安全评估 (105)</option>
          </select>
        </div>
      </div>

      <div className="space-y-6">
        <div 
          className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
            isDragging ? 'border-primary bg-primary/5' : 'border-slate-200'
          }`}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
        >
          <div className="flex flex-col items-center justify-center space-y-3">
            <FileUp className="h-10 w-10 text-slate-400" />
            {selectedFile ? (
              <div className="flex items-center space-x-2">
                <span className="text-sm font-medium text-slate-700">
                  {selectedFile.name}
                </span>
                <button
                  type="button"
                  onClick={handleRemoveFile}
                  className="text-slate-400 hover:text-slate-600"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>
            ) : (
              <div className="text-sm text-slate-500">
                <label
                  htmlFor="file-upload"
                  className="relative cursor-pointer rounded-md font-medium text-primary hover:text-primary/80 focus-within:outline-none"
                >
                  <span>点击上传</span>
                  <input
                    id="file-upload"
                    name="file-upload"
                    type="file"
                    className="sr-only"
                    accept=".xlsx,.xls,.csv"
                    onChange={handleFileChange}
                  />
                </label>
                <span className="pl-1">或将文件拖拽到此处</span>
              </div>
            )}
            <p className="text-xs text-slate-400">
              支持 Excel 或 CSV 文件，大小不超过 10MB
            </p>
          </div>
        </div>

        <div className="flex justify-end">
          <button
            type="button"
            onClick={downloadTemplate}
            className="mr-4 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
          >
            <Download className="mr-2 h-4 w-4" />
            下载模板
          </button>
          <button
            type="button"
            onClick={handleUpload}
            disabled={!selectedFile || isLoading}
            className={`inline-flex items-center rounded-md border border-transparent px-4 py-2 text-sm font-medium text-white shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ${
              !selectedFile || isLoading
                ? 'cursor-not-allowed bg-blue-300'
                : 'bg-blue-600 hover:bg-blue-700'
            }`}
          >
            {isLoading ? '上传中...' : '上传并继续'}
          </button>
        </div>
      </div>
    </div>
  );
};
